package com.github.fashionbrot.algorithms;




import com.github.fashionbrot.AuthEncoder;
import com.github.fashionbrot.exception.SignatureVerificationException;
import com.github.fashionbrot.exception.TokenExpiredException;
import com.github.fashionbrot.tlv.TLVUtil;
import com.github.fashionbrot.util.DateUtil;

import java.util.Date;

public abstract class Algorithm {


    public abstract  <T extends AuthEncoder> T decrypt(Class<T> clazz,String token);

    public abstract String encrypt(AuthEncoder authEncoder);


    public static <T extends AuthEncoder> T deserialize(Class<T> clazz, byte[] decrypt) {
        T deserialized = TLVUtil.deserialize(clazz, decrypt);
        if (deserialized==null){
            throw new SignatureVerificationException("Signature verification failure");
        }
        Date issuedAt = deserialized.getIssuedAt();
        Date expiresAt = deserialized.getExpiresAt();
        if (!DateUtil.isDateBetweenInclusive(new Date(),issuedAt,expiresAt)){
            throw new TokenExpiredException("token expired");
        }
        return deserialized;
    }

}
